package net.caixiaomi.info.ui.football;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.mobstat.StatService;

import net.caixiaomi.info.Lottery.ui.LotteryOrderDetailActivity;
import net.caixiaomi.info.R;
import net.caixiaomi.info.adapter.PayWayAdapter;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseActivity;
import net.caixiaomi.info.base.BaseAlertDialog;
import net.caixiaomi.info.base.progressbar.CircularProgressBar;
import net.caixiaomi.info.base.quickadapter.BaseQuickAdapter;
import net.caixiaomi.info.helper.AppHelper;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.CommonEvent;
import net.caixiaomi.info.model.CouponsItem;
import net.caixiaomi.info.model.PayWayItem;
import net.caixiaomi.info.model.PaymentAppModel;
import net.caixiaomi.info.model.PaymentModel;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.ui.dialog.CouponDialogFragment;
import net.caixiaomi.info.ui.order.OrderInfoActivity;
import net.caixiaomi.info.util.Constants;
import net.caixiaomi.info.util.EventWhat;
import net.caixiaomi.info.util.ToastUtil;
import net.caixiaomi.info.widgets.DefLoading;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * 支付订单
 */

public class PaymentActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener {

    @BindView(R.id.order_price)
    TextView mOrderPrice;
    @BindView(R.id.balance_price)
    TextView mBalancePrice;
    @BindView(R.id.coupon_price)
    TextView mCouponPrice;
    @BindView(R.id.need_price)
    TextView mNeedPrice;
    @BindView(R.id.more)
    View mMore;
    @BindView(android.R.id.list)
    RecyclerView mListView;
    @BindView(R.id.progress)
    CircularProgressBar mProgress;
    @BindView(R.id.btn_pay)
    View mBtnPay;
    @BindView(R.id.view1)
    View mBtnCoupon;
    @BindView(R.id.pay_title)
    View mPayTitle;

    private PaymentModel mPaymentModel;

//    private JSONObject mParams;

    private PayWayAdapter mAdapter;
    private boolean isThirdPay = false;
    private String mPayLogId = "";
    private String mOrderId = "";
    private boolean mPayFinished = false;
    private int mType = 0;
    private boolean mAction = false;

    @OnClick(R.id.btn_pay)
    void toPay() {
        if (mPaymentModel == null)
            return;
        mPayFinished = false;
        //如果需要第三方支付，
        String payCode = "";
        boolean needThirdPay = new BigDecimal(mPaymentModel.getThirdPartyPaid()).compareTo(new BigDecimal("0")) == 1;
        if (needThirdPay) {
            if (mAdapter.getData().isEmpty())
                return;
            Iterator<PayWayItem> iterator = mAdapter.getData().iterator();
            while (iterator.hasNext()) {
                PayWayItem next = iterator.next();
                if (next.isSelected()) {
                    payCode = next.getPayCode();
                    break;
                }
            }
        }
        AppHelper.sendStatistics("querenzhifuzc", new String[]{getString(R.string.C_TYPE_OF_LOTTERY)}, new String[]{getTitleFormType()});
        JSONObject params = new JSONObject();
        params.put("payToken", mPaymentModel.getPayToken());
        params.put("payCode", payCode);params.put("payCode", payCode);

        mLoading.show();
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<PaymentAppModel>> paymentApp = requestService.paymentApp(params);
        paymentApp.enqueue(new ResponseCallback<BaseCallModel<PaymentAppModel>>(this) {
            @Override
            public void onSuccess(BaseCallModel<PaymentAppModel> data) {
                try {
                    setResult(Constants.TYPE_BALL_LOTTERY);
                    mLoading.dismiss();
                    PaymentAppModel model = data.data;
                    //TODO 这块处理不正常
                    if (new BigDecimal(mPaymentModel.getThirdPartyPaid()).compareTo(new BigDecimal("0")) == 1) {
                        mPayLogId = model.getPayLogId();
                        mOrderId = model.getOrderId();
                        isThirdPay = true;
                        mBtnPay.setEnabled(false);
                        mBtnCoupon.setEnabled(false);
                        mListView.setEnabled(false);
                        startThirdPay(model.getPayUrl());
                        mProgress.setVisibility(View.VISIBLE);
                    } else {
                        ToastUtil.s(data.msg);
                        toHandlePayFinish(model.getOrderId());
                        mPayFinished = true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(ResponseError error) {
                mLoading.dismiss();
                if (error.getCode() >= 300000 && error.getCode() <= 310000) {
                    ToastUtil.s(error.getMessage());
                }

            }

            @Override
            public void onError() {
                mLoading.dismiss();

            }
        });
    }

    private void toHandlePayFinish(String orderId) {
        toOrderInfo(orderId);
        EventBus.getDefault().post(new CommonEvent(EventWhat.EVENT_PAYMENT));
        onBackPressed();
    }

    private void startThirdPay(String payUrl) {
        Uri uri = Uri.parse(payUrl);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }


    @OnClick({R.id.more, R.id.coupon_price})
    void toSelectCoupon() {
        try {
            if (mPaymentModel == null)
                return;

            List<CouponsItem> bonusList = mPaymentModel.getBonusList();
            if (bonusList.isEmpty())
                return;
            AppHelper.sendStatistics("youhuiquanzc", new String[]{getString(R.string.C_TYPE_OF_LOTTERY)}, new String[]{getTitleFormType()});
            CouponDialogFragment dialog = new CouponDialogFragment();
            Bundle bundle = new Bundle();
            bundle.putString("data", JSON.toJSONString(bonusList));
            dialog.setArguments(bundle);
            dialog.show(getSupportFragmentManager(), dialog.getClass().getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected int layout() {
        return R.layout.act_pay;
    }

    private String payToken;
    private String bonusId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mLoading = new DefLoading(this);
//        String strData = getIntent().getStringExtra("data");
        mAction = getIntent().getBooleanExtra("action", false);
//        if (!TextUtils.isEmpty(strData)) {
//            mParams = JSON.parseObject(strData);
//            mType = mParams.getIntValue("lotteryPlayClassifyId");
//
//        }
        payToken=getIntent().getStringExtra("payToken");
        mType=getIntent().getIntExtra("type",0);

        if(!TextUtils.isEmpty(payToken)){
            unifiedPayBefore();
        }

        mListView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new PayWayAdapter(R.layout.item_pay_way);
        mAdapter.setOnItemClickListener(this);
        mListView.setAdapter(mAdapter);
        mLoading = new DefLoading(this);
//        calculatePrice();
        loadPayWay();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isThirdPay) {
            mCountDownTimer.start();
        }
        StatService.onPageStart(this, "zhifu-view");
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPageEnd(this, "zhifu-view");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCountDownTimer.cancel();
        mCountDownTimer = null;
//        mParams = null;
    }

    @Override
    public void onPostEvent(CommonEvent event) {
        try {
            switch (event.getWhat()) {
                case EventWhat.EVENT_TAKE_ORDER_SELECT_COUPON:
                    String message = event.getMessage();
                    CouponsItem item = JSON.parseObject(message, CouponsItem.class);
//                    mParams.put("bonusId", item.getUserBonusId());
                    bonusId=item.getUserBonusId();
                    unifiedPayBefore();
                    mLoading.show();
//                    calculatePrice();
                    break;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void unifiedPayBefore(){
        try {
            RequestService requestService = RetrofitManage.getInstance().getRequestService();
            JSONObject params = new JSONObject();
            params.put("bonusId", TextUtils.isEmpty(bonusId)?"":bonusId); //
            params.put("payToken", payToken);  //
            Call<BaseCallModel<PaymentModel>> unifiedPayBefore=requestService.unifiedPayBefore(params);
            unifiedPayBefore.enqueue(new ResponseCallback<BaseCallModel<PaymentModel>>() {
                @Override
                public void onSuccess(BaseCallModel<PaymentModel> data) {
                    mLoading.dismiss();
                    PaymentModel model = data.data;
                    mPaymentModel = model;
                    bindData(model);
                }

                @Override
                public void onFail(ResponseError error) {
                    mLoading.dismiss();
                    if (error.getCode() >= 300000 && error.getCode() <= 310000) {
                        ToastUtil.s(error.getMessage());
                    }
                }

                @Override
                public void onError() {
                    mLoading.dismiss();
                }
            });
        }catch (Exception e){

        }
    }

//    private void calculatePrice() {
//        try {
//            RequestService requestService = RetrofitManage.getInstance().getRequestService();
//            Call<BaseCallModel<PaymentModel>> saveBetInfo = mAction ? requestService.saveBetInfoWordCup(mParams) : requestService.saveBetInfo(mParams);
//            saveBetInfo.enqueue(new ResponseCallback<BaseCallModel<PaymentModel>>(this) {
//                @Override
//                public void onSuccess(BaseCallModel<PaymentModel> data) {
//                    mLoading.dismiss();
//                    PaymentModel model = data.data;
//                    mPaymentModel = model;
//                    bindData(model);
//                }
//
//                @Override
//                public void onFail(ResponseError error) {
//                    mLoading.dismiss();
//                    if (error.getCode() >= 300000 && error.getCode() <= 310000) {
//                        ToastUtil.s(error.getMessage());
//                    }
//                }
//
//                @Override
//                public void onError() {
//                    mLoading.dismiss();
//                }
//            });
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    private void loadPayWay() {
        JSONObject params = new JSONObject();
        params.put("time", System.currentTimeMillis());
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<List<PayWayItem>>> saveBetInfo = requestService.allPayment(params);
        saveBetInfo.enqueue(new ResponseCallback<BaseCallModel<List<PayWayItem>>>(this) {
            @Override
            public void onSuccess(BaseCallModel<List<PayWayItem>> data) {
                try {
                    List<PayWayItem> list = data.data;
                    if (!list.isEmpty()) {
                        list.get(0).setSelected(true);
                    }
                    mAdapter.setNewData(list);

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFail(ResponseError error) {
            }

            @Override
            public void onError() {
            }
        });
    }

    private void paymentQuery(String payLogId) {
        if (mPayFinished)
            return;
        JSONObject params = new JSONObject();
        params.put("payLogId", payLogId);
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel> paymentQuery = requestService.paymentQuery(params);
        paymentQuery.enqueue(new ResponseCallback<BaseCallModel>(this) {
            @Override
            public void onSuccess(BaseCallModel data) {
                if (mPayFinished)
                    return;
                isThirdPay = false;
                mPayFinished = true;
                mProgress.setVisibility(View.GONE);
                ToastUtil.s(data.msg);
                toHandlePayFinish(mOrderId);
            }

            @Override
            public void onFail(ResponseError error) {
                try {
                    if (mPayFinished)
                        return;
                    if (error.getCode() >= 300000 && error.getCode() <= 310000) {
                        if (error.getCode() == 304035) {//融宝支付失败
                            mBtnPay.setEnabled(true);
                            mBtnCoupon.setEnabled(true);
                            mListView.setEnabled(true);
                            mProgress.setVisibility(View.GONE);
                            isThirdPay = false;
                            mPayFinished = true;
                            mCountDownTimer.cancel();
                            showDialogNotice(error.getMessage());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError() {
            }
        });
    }

    private void bindData(PaymentModel model) {
        try {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(getString(R.string.C_MONEY_CHAT)).append(model.getOrderMoney());
            String orderMoney = stringBuilder.toString();
            stringBuilder.setLength(0);
            mOrderPrice.setText(orderMoney);
            stringBuilder.append("- ").append(getString(R.string.C_MONEY_CHAT)).append(model.getSurplus());
            String balanceMoney = stringBuilder.toString();
            stringBuilder.setLength(0);
            mBalancePrice.setText(balanceMoney);

            stringBuilder.append("- ").append(getString(R.string.C_MONEY_CHAT)).append(model.getBonusAmount());
            String couponMoney = stringBuilder.toString();
            stringBuilder.setLength(0);
            mCouponPrice.setText(couponMoney);

            stringBuilder.append("").append(getString(R.string.C_MONEY_CHAT)).append(model.getThirdPartyPaid());
            String needMoney = stringBuilder.toString();
            stringBuilder.setLength(0);
            mNeedPrice.setText(needMoney);
            mMore.setVisibility(model.getBonusList().isEmpty() ? View.GONE : View.VISIBLE);
            boolean needThirdPay = new BigDecimal(model.getThirdPartyPaid()).compareTo(new BigDecimal("0")) == 1;
            mListView.setVisibility(needThirdPay ? View.VISIBLE : View.GONE);
            mPayTitle.setVisibility(needThirdPay ? View.VISIBLE : View.GONE);

            AppHelper.sendStatistics(needThirdPay ? "wxzhifuzc" : "yuedikouzc", new String[]{getString(R.string.C_TYPE_OF_LOTTERY)}, new String[]{getTitleFormType()});

            List<CouponsItem> bonusList = model.getBonusList();
            if (!bonusList.isEmpty()) {
                Iterator<CouponsItem> iterator = bonusList.iterator();
                while (iterator.hasNext()) {
                    CouponsItem next = iterator.next();
                    if (TextUtils.equals(next.getUserBonusId(), model.getBonusId())) {
                        next.setSelected(true);
                        break;
                    }
                }

                CouponsItem noUse = new CouponsItem();
                noUse.setUserBonusId("-1");
                noUse.setBonusPrice(getString(R.string.C_NO_USE_COUPON));
                bonusList.add(noUse);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void toOrderInfo(String id) {
        if(mType==Constants.TYPE_BALL_LOTTERY) {
            Intent intent = new Intent(this, LotteryOrderDetailActivity.class);
            intent.putExtra("id", id);
            startActivity(intent);
            //------
            CommonApp.mLotteryIndex=-1;
            CommonApp.mLotteryBettingList.clear();

        }else {
            Intent intent = new Intent(this, OrderInfoActivity.class);
            intent.putExtra("id", id);
            startActivity(intent);
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        try {
            PayWayItem item = mAdapter.getData().get(position);
            if (item.isSelected())
                return;
            AppHelper.sendStatistics("wxzhifuzc", new String[]{getString(R.string.C_TYPE_OF_LOTTERY)}, new String[]{item.getPayName()});
            Iterator<PayWayItem> iterator = mAdapter.getData().iterator();
            while (iterator.hasNext()) {
                PayWayItem next = iterator.next();
                next.setSelected(false);
            }
            mAdapter.getData().get(position).setSelected(true);
            mAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showDialogNotice(String message) {
        BaseAlertDialog dialog = new BaseAlertDialog(this);
        dialog.setMessage(message);
        dialog.setPositiveButton(R.string.C_I_KNOW, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        dialog.show();
    }

    private CountDownTimer mCountDownTimer = new CountDownTimer(5 * 1000, 3000) {
        @Override
        public void onTick(long millisUntilFinished) {
            paymentQuery(mPayLogId);
        }

        @Override
        public void onFinish() {
            try {
                if (mPayFinished)
                    return;
                mPayFinished = true;
                mProgress.setVisibility(View.GONE);
                mBtnPay.setEnabled(true);
                mBtnCoupon.setEnabled(true);
                mListView.setEnabled(true);
                isThirdPay = false;
                showDialogNotice(getString(R.string.C_ORDER_SEARCH_FAIL));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };


    private String getTitleFormType() {
        String title = "";
        switch (mType) {
            case Constants.TYPE_VICTORY_AND_DEFEAT:
                title = getString(R.string.C_VICTORY_AND_DEFEAT);
                break;
            case Constants.TYPE_VICTORY_AND_DEFEAT_1:
                title = getString(R.string.C_VICTORY_AND_DEFEAT_1);
                break;
            case Constants.TYPE_ALL_GOALS:
                title = getString(R.string.C_ALL_GOALS);
                break;
            case Constants.TYPE_HALF_AND_ALL:
                title = getString(R.string.C_HALF_AND_ALL);
                break;
            case Constants.TYPE_SCORE:
                title = getString(R.string.C_SCORE);
                break;
            case Constants.TYPE_BLEND:
                title = getString(R.string.C_BLEND);
                break;
            case Constants.TYPE_2_IN_1:
                title = getString(R.string.C_2_IN_1);
                break;
        }
        return title;
    }

    @Override
    public void onBackPressed() {
        AppHelper.sendStatistics("zhifufanhuizc", new String[]{getString(R.string.C_TYPE_OF_LOTTERY)}, new String[]{getTitleFormType()});
        super.onBackPressed();
    }
}
